/**
 * 微信授权登录工具类
 */

// 检查是否在微信环境中
export const isWechat = () => {
  return /micromessenger/i.test(navigator.userAgent);
};

// 获取微信授权URL
export const getWechatAuthUrl = (appId, redirectUri, state = '') => {
  const encodedRedirectUri = encodeURIComponent(redirectUri);
  const encodedState = encodeURIComponent(state);
  
  return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${encodedRedirectUri}&response_type=code&scope=snsapi_userinfo&state=${encodedState}#wechat_redirect`;
};

// 从URL中获取微信授权码
export const getWechatCode = () => {
  const urlParams = new URLSearchParams(window.location.search);
  const code = urlParams.get('code');
  return code;
};

// 从URL中获取微信授权状态
export const getWechatState = () => {
  const urlParams = new URLSearchParams(window.location.search);
  return urlParams.get('shopId');
};

export const getUrlParams = (key) => {
  const urlParams = new URLSearchParams(window.location.search);
  return urlParams.get(key) || null;
};

// 检查是否从微信授权回调
export const isWechatAuthCallback = () => {
  return !!getWechatCode();
};

// 清除URL中的微信授权参数
export const clearWechatAuthParams = () => {
  const url = new URL(window.location.href);
  url.searchParams.delete('code');
  url.searchParams.delete('state');
  window.history.replaceState({}, document.title, url.pathname + url.search);
};

// 微信授权登录类
export class WechatAuth {
  constructor(appId, apiBaseUrl) {
    this.appId = appId;
    this.apiBaseUrl = apiBaseUrl;
  }

  // 开始授权登录
  async startAuth(redirectUri, state = '') {
    if (!isWechat()) {
      throw new Error('请在微信中打开');
    }

    // 如果已经在授权回调中，直接处理
    if (isWechatAuthCallback()) {
      return await this.handleAuthCallback();
    }

    // 否则跳转到授权页面
    const authUrl = getWechatAuthUrl(this.appId, redirectUri, state);
    window.location.href = authUrl;
    return null;
  }

  // 处理授权回调
  async handleAuthCallback() {
    const code = getWechatCode();
    const state = getWechatState();

    if (!code) {
      throw new Error('未获取到微信授权码');
    }

    try {
      // 调用后端接口获取用户信息
      const response = await fetch(`${this.apiBaseUrl}/api/wechat/auth`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          code,
          state
        })
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      
      // 清除URL中的授权参数
      clearWechatAuthParams();
      
      return data;
    } catch (error) {
      console.error('微信授权登录失败:', error);
      throw error;
    }
  }

  // 检查登录状态
  async checkLoginStatus() {
    try {
      const token = localStorage.getItem('wechat_token');
      if (!token) {
        return null;
      }

      const response = await fetch(`${this.apiBaseUrl}/api/user/profile`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (!response.ok) {
        // token无效，清除本地存储
        this.logout();
        return null;
      }

      const userInfo = await response.json();
      return userInfo;
    } catch (error) {
      console.error('检查登录状态失败:', error);
      return null;
    }
  }

  // 退出登录
  logout() {
    localStorage.removeItem('wechat_token');
    localStorage.removeItem('user_info');
  }

  // 获取本地存储的用户信息
  getUserInfo() {
    const userInfoStr = localStorage.getItem('user_info');
    if (userInfoStr) {
      try {
        return JSON.parse(userInfoStr);
      } catch (error) {
        console.error('解析用户信息失败:', error);
        return null;
      }
    }
    return null;
  }

  // 保存用户信息到本地存储
  saveUserInfo(userInfo, token) {
    localStorage.setItem('user_info', JSON.stringify(userInfo));
    if (token) {
      localStorage.setItem('wechat_token', token);
    }
  }
}

// 创建微信授权实例
export const createWechatAuth = (appId, apiBaseUrl) => {
  return new WechatAuth(appId, apiBaseUrl);
};
